package com.xbn.netty.simpleHttp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author XBN
 * @date 2020/10/20 15:26
 * @email 78742541@qq.com
 */
/*
* SimpleChannelInboundHandler其实就是ChannelInboundHandlerAdapter的子类
* HttpObject表示的是客户端和服务器端相互通讯的数据被封装成HttpObject类型(这里是客户端发送过来的数据)
* */
public class HttpTestServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //channel read0读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
            if(httpObject instanceof HttpRequest)
            {
                HttpRequest request= (HttpRequest) httpObject;
                URI uri = new URI(request.uri());
                if("/favicon.ico".equals(uri.getPath()))
                {
                    System.out.println("请求了favicon.ico");
                    return;
                }
                //得到客户端的地址
                System.out.println("客户端地址"+channelHandlerContext.channel().remoteAddress());
                //回复信息给浏览器，需要满足http协议
                ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);
                //构造一个http的响应，也就是httpResponse
                FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK, content);
                //设置文本形式
                httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
                //设置内容长度
                httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
                //将构建好的响应返回
                channelHandlerContext.writeAndFlush(httpResponse);

            }
    }
}
